package com.bwie.config;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author 小薛超人
 * @version 1.0
 * @description: TODO
 * @date 2025/7/18 16:50
 */
@Configuration
@Order(1)
public class MyFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        System.out.println("url:"+url);

        //白名单
        if(url.contains("/sendCode") || url.contains("/enrollUser") || url.contains("/userLogin") || url.contains("/uploadImages")){
            System.out.println("白名单:"+url);
            return chain.filter(exchange);
        }

        //得到token
        String token = request.getHeaders().getFirst("token");
        if(token == null){
            System.out.println("token为空："+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //从redis中取得token---解析token
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String keys = "token-"+userId;
        String redisToken = redisTemplate.opsForValue().get(keys);

        if(redisToken == null){
            System.out.println("token已过期："+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if(!redisToken.equals(token)){
            System.out.println("token错误："+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //续期
        redisTemplate.expire(keys,60, TimeUnit.MINUTES);

        //放行
        System.out.println("放行："+url);
        return chain.filter(exchange);

    }
}
